import React, { Component } from 'react'
import Taro,{Current} from '@tarojs/taro'
import { View,Text,Image } from '@tarojs/components'
import { AtSearchBar } from 'taro-ui'
import { TabsInHospAndDept } from '../../../components/navigation/TabsInHospAndDept'
import {api_get_hospitals , api_get_department,api_get_hospitals_by_location } from '../../../utils/api'
import './selectHospOrDept.scss'

export default class selectHospOrDept extends Component {

  constructor(){
    super(...arguments)
    this.state = {
      hospital_loading:false,
      department_loading:false,
      getting:false,
      value:'',
      region:["","",""],
      showSearch:false,
      hotList: ['同济', '协和', '儿童', '胡志全'],
      hList: Taro.getStorageSync('search_cache')
    }
  }

  getThings =() =>{
    //加载数据
    Taro.showLoading({
      title: '加载中',
    })
    // 界面传参并获取地理位置参数
    Taro.getLocation({type: 'wgs84'}).then(
      (res) => {
        this.setState({
        current:Current.router.params.current,
        location_data:res,
        getting:true
      })
    })
  }

  myRequest =  () => {
    const hospital_params = {
      url: api_get_hospitals,
      data: {
        lat:this.state.location_data.latitude,
        lng:this.state.location_data.longitude,
      },
      method: 'POST',
      header: {'content-type': 'application/x-www-form-urlencoded'},
      success: (res) => {   
        this.setState({
          hospital_data:res.data.hospitalInfor,
          region:res.data.city,
          hospital_loading:true
        }) 
      },
      fail: (res) => {console.log(res.data)}
    }
    const department_params = {
      url: api_get_department,
      data: {},
      method: 'GET',
      header: {'content-type': 'application/json'},
      success: (res) => {
        this.setState({
          department_data:res.data,
          department_loading:true
        }) 
      },
      fail: (res) => {console.log(res.data)}
    }
    Taro.request(hospital_params) 
    Taro.request(department_params)
  }

  afterRequest = () =>{
    const hospital_params_by_location = {
      url: api_get_hospitals_by_location,
      data: {
        province:this.state.region[0],
        city:this.state.region[1]
      },
      method: 'POST',
      header: {'content-type': 'application/x-www-form-urlencoded'},
      success: (res) => {
        this.setState({
          hospital_data:res.data,
          hospital_loading:true
        }) 
      },
      fail: (res) => {console.log(res.data)}
    }
    Taro.request(hospital_params_by_location)
  }

  onChange = (value) => {
    this.setState({
      value: value
    })
  }

  onFocus = () =>{
    this.setState({
      showSearch:true
    })
  }

  onBlur = ()=>{
    this.setState({
      showSearch:false
    })
  }

  onRegionChange = e => {
    this.setState({
      region: e.detail.value
    })
    this.afterRequest()
  }

  onActionClick = () =>{
    let _this = this;
    if (_this.state.value == '') {
        Taro.showToast({
            title: '请输入关键字',
            icon: 'none',
            duration: 1000
        });
    } else {
        this.goNextPage()
        Taro.getStorage({
            key: 'search_cache',
            success(res) {
                // console.log(res)
                let list = res.data;
                if (list.length > 5) {
                    for (let item of list) {
                        if (item == _this.state.value) {
                            return;
                        }
                    }
                    list.pop();
                    list.unshift(_this.state.value);
                } else {
                    for (let item of list) {
                        if (item == _this.state.value) {
                            return;
                        }
                    }
                    list.unshift(_this.state.value);
                }
                _this.setState({
                    hList: list
                }, () => {
                    // console.log(_this.state.hList)
                    Taro.setStorage({
                        key: 'search_cache',
                        data: _this.state.hList
                    });
                })
            },
            fail(err) {
                _this.setState({
                    hList: []
                }, () => {
                    let hList=_this.state.hList
                    hList.push(_this.state.value)
                    _this.setState({
                        hList
                    }, () => {
                        // console.log(_this.state.hList)
                        Taro.setStorage({
                            key: 'search_cache',
                            data: _this.state.hList
                        });
                        _this.goNextPage()
                    })
                })
            }
        })
    }
  }

  goNextPage = () =>{
    const page = '/pages/pagesA/searchResult/searchResult?city='+this.state.region[1]+'&input='+this.state.value
    Taro.navigateTo({url: page})
  }

  
  keywordsClick = (item, e) => {	//关键词搜索与历史搜索
    this.setState({
        value: item
    }, () => {
        this.onActionClick();
    })
}

delhistory = () => {		//清空历史记录
    this.setState({
        hList: []
    }, () => {
        Taro.setStorage({
            key: 'search_cache',
            data: []
        });
    })
}

  render () {
    if(!this.state.getting){
      this.getThings()
    }

    if(this.state.getting && !this.state.hospital_loading){
      this.myRequest()
    }
    if(this.state.hospital_loading && this.state.department_loading){
      setTimeout(function () {Taro.hideLoading()}, 100) 
    }
    return (
      this.state.hospital_loading && this.state.department_loading?
      <View className='selectHospital-page'>
        <View className='at-row'>
          <View className='at-col at-col-2'>
            <picker mode="region" onChange={this.onRegionChange} value="{{region}}">
              <Text className='picker'>{this.state.region[1]}</Text>
            </picker>
          </View>
          <View className='at-col'>
            <AtSearchBar  value={this.state.value} placeholder='请输入医院/医生名' onChange={this.onChange} onFocus={this.onFocus} onBlur={this.onBlur} onActionClick={this.onActionClick}/>
          </View> 
        </View>
        {
          this.state.showSearch?
          this.state.hList.length > 0 ? (
            <View>
            <View className={'s-circle'} >
                <View className="header">
                    历史记录
            <Image src='http://39.106.116.133:8080/images/search/delete.svg' onClick={this.delhistory} mode="aspectFit" ></Image>
                </View>
                <View className="list">
                    {
                        this.state.hList.map((item, index) => {
                            return (<View key={index}  onClick={this.keywordsClick.bind(this, item)}>{item}</View>)
                        })
                    }
                </View>
              </View>
              <View className={'wanted-circle'}>
                <View className="header">猜你想搜的</View>
                <View className="list">
                    {
                        this.state.hotList.map((item, index) => {
                            return (
                                <View key={index} onClick={this.keywordsClick.bind(this, item)}>{item}</View>
                            )
                        })
                    }
                </View>
              </View>
            </View>
            ):
            <View className={'wanted-circle'}>
              <View className="header">猜你想搜的</View>
              <View className="list">
                  {
                      this.state.hotList.map((item, index) => {
                          return (
                              <View key={index} onClick={this.keywordsClick.bind(this, item)}>{item}</View>
                          )
                      })
                  }
              </View>
            </View>
          :<TabsInHospAndDept current={this.state.current}
          department_data={this.state.department_data}
          hospital_data={this.state.hospital_data}/>
        }
      </View>
      :<View></View>
    )
  }
}


